package com.txsj.scan.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.greendao.GlobalGoodsInfoDao;
import com.nativec.tools.ModuleManager;
import com.txsj.scan.R;
import com.txsj.scan.activity.allocationapply.AllocationApplyActivity;
import com.txsj.scan.adapter.GoodsInfoAdapter;
import com.txsj.scan.adapter.GoodsLeftAdapeter;
import com.txsj.scan.base.BaseActivity;
import com.txsj.scan.bean.EpcInfo;
import com.txsj.scan.bean.GlobalGoodsInfo;
import com.txsj.scan.bean.GoodsClassify;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.UpdateBean;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.presenter.GoodsListPresenter;
import com.txsj.scan.reader.setpage.Setting;
import com.txsj.scan.refresh.XRefreshView;
import com.txsj.scan.utils.PreferenceUtil;
import com.txsj.scan.utils.SDLguiUtils;
import com.txsj.scan.utils.Trace;
import com.txsj.scan.utils.glide.GlideImgManager;
import com.txsj.scan.view.IGoodsListView;
import com.txsj.scan.widget.TSnackbarView;
import com.txsj.scan.widget.TextViewFont;
import com.txsj.scan.widget.dialog.ChangeSelectedGoodsListDialog;
import com.txsj.scan.widget.dialog.CustomDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangchuangjun on 2019/2/18
 * Desc: 选择商品列表页
 */

public class SelectGoodsListActivity extends BaseActivity<GoodsListPresenter> implements IGoodsListView, View.OnClickListener {

    public static final int REQUEST_SEARCH_CODE = 0x081;
    public static final int REQUEST_PERMISSION_CODE = 0x082;

    private TextView login_out, tv_user_name, tv_brandName, tv_update,
            tv_setting, tv_refresh, tv_to_scan, tv_to_allocate;
    private TextView tv_to_allocateApply;
    private ImageView iv_wshop_logo, iv_search_goods;

    private TextViewFont tv_menu;
    private DrawerLayout mDrawerLayout;
    private NavigationView navigationView;

    private RecyclerView type_recyclerView, goods_recyclerView;
    private TextView tv_select_all_count, cancel_selected;
    private XRefreshView xRefreshView;
    private GoodsLeftAdapeter leftAdapeter;
    private GoodsInfoAdapter goodsInfoAdapter;
    private Activity activity;
    private RelativeLayout titleLay;
    private LinearLayout lay_confirm;

    List<GoodsInfo> selectGoodsInfoList;//点击选中的商品列表

    int pageNo = 1;
    int classifyPosition = 0;

    boolean isGoodsTypeLoading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_goods_list);
        activity = this;
        initView();
        initData();
    }



    private void initData() {
        selectGoodsInfoList = new ArrayList<>();
        GlideImgManager.getLoadCircleImg(this, PreferenceUtil.getInstance().getString
                (PreferenceUtil.LOGO, ""), iv_wshop_logo);
        tv_user_name.setText(PreferenceUtil.getInstance().getString(PreferenceUtil.ROLE, ""));
        tv_brandName.setText(PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_NAME, ""));
        //初始化商品分类列表
        presenter.getGoodsTypeHttp();

        //缓存当前品牌下所有商品
        presenter.cacheGoodsList();

        //检测版本更新
        toCheckUpdate();
    }

    private void initView() {
        titleLay = findViewById(R.id.mTitle);
        tv_refresh = (TextView) findViewById(R.id.tv_refresh);
        tv_menu = (TextViewFont) findViewById(R.id.tv_menu);
        tv_select_all_count = (TextView) findViewById(R.id.tv_select_all_count);
        cancel_selected = (TextView) findViewById(R.id.cancel_selected);
        lay_confirm = (LinearLayout) findViewById(R.id.lay_confirm);
        iv_search_goods = (ImageView) findViewById(R.id.iv_search_goods);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);

        login_out = (TextView) navigationView.findViewById(R.id.login_out);
        tv_setting = (TextView) navigationView.findViewById(R.id.tv_setting);
        tv_update = (TextView) navigationView.findViewById(R.id.tv_update);
        tv_to_scan = (TextView) navigationView.findViewById(R.id.tv_to_scan);
        tv_to_allocate = (TextView) navigationView.findViewById(R.id.tv_to_allocate);
        tv_to_allocateApply = (TextView) navigationView.findViewById(R.id.tv_to_allocateApply);
        iv_wshop_logo = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.iv_wshop_logo);
        tv_user_name = (TextView) navigationView.getHeaderView(0).findViewById(R.id.tv_user_name);
        tv_brandName = (TextView) navigationView.getHeaderView(0).findViewById(R.id.tv_brandName);

        type_recyclerView = (RecyclerView) findViewById(R.id.type_recyclerView);
        goods_recyclerView = (RecyclerView) findViewById(R.id.goods_recyclerView);
        xRefreshView = (XRefreshView) findViewById(R.id.xRefreshView);

        initEmptyView();
        xRefreshView.enableEmptyView(false);
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setAutoLoadMore(true);

        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                super.onRefresh(isPullDown);
                pageNo = 1;
                if (leftAdapeter.getList().size() > 0) {
                    presenter.getGoodsList(leftAdapeter.getList().get(classifyPosition).getGoods_class_id(), pageNo, "-1", "0");
                }

            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
//                pageNo++;//如果加载失败，pageNo++只会无尽的自增
                if (goodsInfoAdapter.getList().size() % 20 != 0 || leftAdapeter.getList().size() <= 0) {
                    xRefreshView.stopLoadMore();
                    return;
                }
                presenter.getGoodsList(leftAdapeter.getList().get(classifyPosition).getGoods_class_id(), pageNo, "-1", "0");
            }
        });

        type_recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        leftAdapeter = new GoodsLeftAdapeter(activity);
        type_recyclerView.setAdapter(leftAdapeter);
        leftAdapeter.setOnItemListener(new GoodsLeftAdapeter.OnItemListener() {
            @Override
            public void onClick(View v, int pos) {
                if (classifyPosition == pos) return;
                classifyPosition = pos;
                pageNo = 1;
                leftAdapeter.setSelect(pos);
                goodsInfoAdapter.clear();
                xRefreshView.startRefresh();
//                presenter.getGoodsList(leftAdapeter.getList().get(pos).getGoods_class_id(), pageNo, "-1", "0");
            }
        });

        goods_recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        goodsInfoAdapter = new GoodsInfoAdapter(activity);
        goods_recyclerView.setAdapter(goodsInfoAdapter);
        goodsInfoAdapter.setOnSecondItemClickListener(new GoodsInfoAdapter.ISetOnNewSecondClick() {

            @Override
            public void onCheckChange(int position) {
                if (selectGoodsInfoList.size() == 10 && !goodsInfoAdapter.get(position).isSelected()) {
                    showErrorMsg("每次选择的商品数量不能超过10个");
                } else {
                    goodsInfoAdapter.updateRightData(position);//设置选中状态
                    changeGoodsInfoSelectState(goodsInfoAdapter.get(position));//在Adapter更新完毕后获取最新的选中状态
                }
            }
        });

        tv_menu.setOnClickListener(this);
        login_out.setOnClickListener(this);
        tv_setting.setOnClickListener(this);
        tv_refresh.setOnClickListener(this);
        tv_update.setOnClickListener(this);
        lay_confirm.setOnClickListener(this);
        cancel_selected.setOnClickListener(this);
        iv_search_goods.setOnClickListener(this);
        tv_to_scan.setOnClickListener(this);
        tv_to_allocate.setOnClickListener(this);
        tv_to_allocateApply.setOnClickListener(this);
    }

    /**
     * 根据最新的选择状态判断是否添加到选中的集合中去
     * 新的添加，旧的状态替换
     *
     * @param goodsInfo
     */
    private void changeGoodsInfoSelectState(GoodsInfo goodsInfo) {
        if (goodsInfo.isSelected()) {
            selectGoodsInfoList.add(goodsInfo);
        } else {
            boolean isContain = false;
            int pos = -1;
            for (int i = 0; i < selectGoodsInfoList.size(); i++) {
                if (selectGoodsInfoList.get(i).getGoods_id() == goodsInfo.getGoods_id()) {
                    isContain = true;
                    pos = i;
                    break;
                }
            }
            if (isContain) {
                selectGoodsInfoList.remove(pos);
            }
        }

        tv_select_all_count.setText(selectGoodsInfoList.size() + "");
    }

    @Override
    protected GoodsListPresenter providePresenter() {
        return presenter = new GoodsListPresenter(this);
    }


    @Override
    public Context context() {
        return this;
    }

    public void clickOkCommit() {
        if (selectGoodsInfoList.size() == 0) return;
        Intent intent = new Intent(this, ReadLabelActivity.class);
        intent.putExtra("data", new Gson().toJson(selectGoodsInfoList));
        intent.putExtra("from", "SelectGoodsListActivity");
        intent.putExtra("type", "0");
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_menu:
                mDrawerLayout.openDrawer(Gravity.LEFT);
                break;
            case R.id.login_out:
                loginOut();
                break;
            case R.id.tv_setting:
                toSetting();
                break;
            case R.id.lay_confirm:
                clickOkCommit();
                break;
            case R.id.tv_refresh:
                if (!isGoodsTypeLoading) {
                    isGoodsTypeLoading = true;
                    //初始化商品分类列表
                    presenter.getGoodsTypeHttp();
                }
                break;
            case R.id.cancel_selected:
                if (selectGoodsInfoList.size() == 0) {
                    showErrorMsg("请选择商品后进行查看");
                    return;
                }
                changeSelectedList();
                break;
            case R.id.tv_update:
                mDrawerLayout.closeDrawer(navigationView);
                loadLabelAndGoods();
                break;
            case R.id.iv_search_goods:
                Intent intent = new Intent(SelectGoodsListActivity.this, SearchGoodsListActivity.class);
                startActivityForResult(intent, REQUEST_SEARCH_CODE);
                break;
            case R.id.tv_to_scan://跳过选商品直接扫描
                if (GreenDaoUtils.getmDaoSession().getGlobalGoodsInfoDao().loadAll().size() == 0) {
                    showErrorMsg("正在更新数据请稍后。。。");
                    presenter.cacheGoodsList();
                } else {
                    Intent intent1 = new Intent(this, ReadLabelActivity.class);
                    intent1.putExtra("from", "SelectGoodsListActivity");
                    intent1.putExtra("data", "暂时没有");
                    intent1.putExtra("type", "1");
                    startActivity(intent1);
                }
                mDrawerLayout.closeDrawer(navigationView);
                break;
            case R.id.tv_to_allocate://调拨单
                Intent intent1 = new Intent(this, AllocateHistoryActivity.class);
                startActivity(intent1);
                mDrawerLayout.closeDrawer(navigationView);
                break;
            case R.id.tv_to_allocateApply://调拨申请单
                startActivity(AllocationApplyActivity.class);
                mDrawerLayout.closeDrawer(navigationView);
                break;
        }
    }

    /**
     * 操作已选中的商品
     */
    private void changeSelectedList() {
        ChangeSelectedGoodsListDialog dialog = new ChangeSelectedGoodsListDialog(SelectGoodsListActivity.this, selectGoodsInfoList);
        dialog.setListener(new ChangeSelectedGoodsListDialog.Listener() {
            @Override
            public void onConfirm(List<GoodsInfo> list) {
                selectGoodsInfoList = list;
                tv_select_all_count.setText(selectGoodsInfoList.size() + "");
                xRefreshView.startRefresh();
            }
        });
        dialog.show();
        dialog.setCanceledOnTouchOutside(false);//此方法必须在show方法调用之后才起作用
    }

    //重新缓存和加载数据信息
    private void loadLabelAndGoods() {
        PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.FIRST_LOAD_LABEL_AND_GOODS, true);
        PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.LABEL_IS_LOADED, false);//本地记录加载失败
        PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.GOODS_IS_LOADED, false);//本地记录加载失败
        GreenDaoUtils.getSingleTon().deleteAll();
        presenter.getGoodsAndTagHttp();
    }

    /**
     * 退出登录
     */
    private void loginOut() {
        AlertDialog dialog = new AlertDialog.Builder(context())
                .setTitle("确定退出登录？")
                .setCancelable(true)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        PreferenceUtil.getInstance().removeAll();
                        GreenDaoUtils.getSingleTon().deleteAll(true);
                        ModuleManager.newInstance().setUHFStatus(false);
                        Intent intent = new Intent(SelectGoodsListActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .create();
        dialog.show();

    }

    /**
     * 扫码枪设置
     */
    private void toSetting() {
        Intent intent = new Intent(SelectGoodsListActivity.this, Setting.class);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == data || null == data.getStringExtra("data")) return;
        if (requestCode == REQUEST_SEARCH_CODE) {
            GoodsInfo goodsInfo = new Gson().fromJson(data.getStringExtra("data"), GoodsInfo.class);
            //对请求回来的数据进行去重操作
            combineData(goodsInfo);
        }
    }

    /**
     * 请求回来的数据可能有已选中的，需要去重
     *
     * @param goodsInfo
     */
    private void combineData(GoodsInfo goodsInfo) {
        goodsInfo.setSelected(true);
        boolean isContain = false;
        for (GoodsInfo info : selectGoodsInfoList) {
            if (info.getGoods_id() == goodsInfo.getGoods_id()) {
                isContain = true;
            }
        }
        if (!isContain) {
            //去玩重复的后，如果不包含则去添加
            selectGoodsInfoList.add(goodsInfo);
        }
        tv_select_all_count.setText(selectGoodsInfoList.size() + "");
    }

    @Override
    public void onError(String msg) {
        hideLoading();
        showErrorMsg(msg);
        isGoodsTypeLoading = false;
    }

    public void showErrorMsg(String msg) {
        new TSnackbarView(titleLay, msg);
    }

    @Override
    public void onLoadMoreError(String msg) {
        //加载更多失败
        hideLoading();
        xRefreshView.stopRefresh();
        xRefreshView.stopLoadMore();
        xRefreshView.enableEmptyView(false);
    }

    @Override
    public void onLoadError(String msg) {
        //商品第一次加载失败
        hideLoading();
        xRefreshView.stopRefresh();
        xRefreshView.stopLoadMore();
        xRefreshView.enableEmptyView(true);
    }

    @Override
    public void onLoadMoreEnd(String msg) {
        //商品不是第一次，加载结束
        hideLoading();
        xRefreshView.stopRefresh();
        xRefreshView.stopLoadMore();
        xRefreshView.enableEmptyView(false);
    }

    @Override
    public void onEmpty(String msg) {
        //商品第一次加载为空
        hideLoading();
        xRefreshView.stopRefresh();
        xRefreshView.stopLoadMore();
        xRefreshView.enableEmptyView(true);
    }

    @Override
    public void onLoadCacheSuccess() {
//        if (PreferenceUtil.getInstance().getBoolean(PreferenceUtil.GOODS_IS_LOADED, false)
//                && PreferenceUtil.getInstance().getBoolean(PreferenceUtil.LABEL_IS_LOADED, false)) {
//            PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.FIRST_LOAD_LABEL_AND_GOODS, false);
//            hideLoading();
//        }

        if (PreferenceUtil.getInstance().getBoolean(PreferenceUtil.LABEL_IS_LOADED, false)) {
            PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.FIRST_LOAD_LABEL_AND_GOODS, false);
            hideLoading();
        }
    }

    private void toCheckUpdate() {
        presenter.checkVersion();
    }

    @Override
    public void onLoadCacheError(String msg) {
        onError(msg);
    }

    @Override
    public void onLoading() {
        showLoading();
    }

    @Override
    public void onClassifySuccess(List<GoodsClassify> data) {
        hideLoading();
        isGoodsTypeLoading = false;
        leftAdapeter.setData(data);
        classifyPosition = 0;
        leftAdapeter.setSelect(classifyPosition);
        xRefreshView.startRefresh();
    }

    @Override
    public void onGoodsInfoListSuccess(List<GoodsInfo> data) {
        hideLoading();
        xRefreshView.stopRefresh();
        xRefreshView.stopLoadMore();

        xRefreshView.enableEmptyView(false);
        goodsInfoAdapter.setRightListData(setSelectedToList(data), pageNo, leftAdapeter.getList().get(classifyPosition).getClass_name());
        //在加载成功后进行pageNo++
        pageNo++;
    }

    /**
     * 将数据进行选中标识，可能在下拉刷新的时候，数据重置
     * 通过再次筛选将数据选中状态设置进去
     *
     * @param data
     * @return
     */
    private List<GoodsInfo> setSelectedToList(List<GoodsInfo> data) {
        tv_select_all_count.setText(selectGoodsInfoList.size() + "");
        if (selectGoodsInfoList.size() == 0) {
            return data;
        }
        for (GoodsInfo goodsInfo : selectGoodsInfoList) {
            for (GoodsInfo info : data) {
                if (goodsInfo.getGoods_id() == info.getGoods_id()) {
                    info.setSelected(true);
                    break;
                }
            }
        }
        return data;
    }

    Button btn_empty_reload;

    /**
     * 列表数据为空时 显示的View
     */
    private void initEmptyView() {
        View emptyView = View.inflate(activity, R.layout.view_empty, null);
        emptyView.setBackgroundColor(getResources().getColor(R.color.white));
        btn_empty_reload = (Button) emptyView.findViewById(R.id.btn_empty_reload);
        xRefreshView.setEmptyView(emptyView);
        btn_empty_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xRefreshView.startRefresh();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (wd.isShowing() && PreferenceUtil.getInstance().getBoolean(PreferenceUtil.FIRST_LOAD_LABEL_AND_GOODS, false)) {
                return true;
            }
            askForOut();
            return true;
        } else if (KeyEvent.KEYCODE_F4 == keyCode) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//判断权限
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    toScanCode();
                } else {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CODE);
                }
            } else {
                toScanCode();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (SDLguiUtils.getInstance(this).getState() == 1) {//如果当前正在扫描，先关闭扫描
            SDLguiUtils.getInstance(this).doDecode();
        }
        SDLguiUtils.getInstance(this).onPause();//确保关闭扫描后进行onPause()回调
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                toScanCode();
            } else {
                showErrorMsg("请开启相应的权限后才能使用此功能");
            }
        }
    }

    private void toScanCode() {
        SDLguiUtils.getInstance(this).setListener(new SDLguiUtils.OnScanListener() {
            @Override
            public void onScanSuccess(String data) {
                Trace.e("wcj:扫描回调=========:" + data);
                isQrCodeOrScanCode(data);
            }

            @Override
            public void onScanError(String errorMsg) {
                Trace.e("wcj:扫描失败=========:" + errorMsg);
                showErrorMsg(errorMsg);
            }
        }).doDecode();
    }

    /**
     * 判断是条码还是二维码
     *
     * @param data
     */
    private void isQrCodeOrScanCode(String data) {
        if (TextUtils.isEmpty(data)) return;
        if (data.matches("[0-9]+")) {
            presenter.getBarCodeHttp(data);
        } else {
            String result = data.split("/")[data.split("/").length - 1];
            presenter.getQrCodeHttp(result);
        }
    }

    @Override
    public void onBarCodeLoadSuccess(GoodsInfo goodsInfo) {
        hideLoading();
        addToSelectList(goodsInfo);
    }

    @Override
    public void onQrCodeLoadSuccess(EpcInfo epcInfo) {
        hideLoading();
        queryGoods(epcInfo);
    }

    @Override
    public void onForceUpdate(final boolean isForceUpdate, final UpdateBean data) {
        CustomDialog dialog = new CustomDialog(this);
        dialog.setTitleStr(getResources().getString(R.string.update_tip));
        dialog.setContent(data.getVersion_info());
        if (isForceUpdate) {
            dialog.setSimpleOkVisiable(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Uri uri = Uri.parse(data.getDownload_url());
                    Intent intent = new Intent(Intent.ACTION_VIEW);
//                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                    intent.setData(uri);
                    // FLAG_ACTIVITY_NEW_TASK 可以保证安装成功时可以正常打开 app
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    if (isForceUpdate) {
                        System.exit(0);
                    }
                }
            });
            dialog.setCanBackPress(false);
        } else {
            dialog.setCancelVisiable();
            dialog.setOkVisiable(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Uri uri = Uri.parse(data.getDownload_url());
                    Intent intent = new Intent(Intent.ACTION_VIEW);
//                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                    intent.setData(uri);
                    // FLAG_ACTIVITY_NEW_TASK 可以保证安装成功时可以正常打开 app
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    if (isForceUpdate) {
                        System.exit(0);
                    }
                }
            });
        }
        dialog.show();
    }

    @Override
    public void noUpdate() {

    }

    /**
     * 添加到已选中的商品中
     *
     * @param goodsInfo
     */
    private void addToSelectList(GoodsInfo goodsInfo) {
        if (!PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, "").equals(goodsInfo.getBrand_id() + "")) {
            showErrorMsg("暂无此商品，请先使用管理端APP添加");
            return;
        }
        goodsInfo.setSelected(true);//设置商品已选中
        for (GoodsInfo info : selectGoodsInfoList) {
            if (goodsInfo.getGoods_id() == info.getGoods_id()) {
                showErrorMsg("该商品已选中");
                return;
            }
        }

        changeGoodsInfoSelectState(goodsInfo);//将扫描到的商品添加到已选商品中
        showErrorMsg("扫描成功，已选中");
    }

    /**
     * 查询商品信息
     *
     * @param epcInfo
     */
    private void queryGoods(EpcInfo epcInfo) {
        List<GlobalGoodsInfo> list = GreenDaoUtils.getSingleTon().getmDaoSession().getGlobalGoodsInfoDao().queryBuilder()
                .where(GlobalGoodsInfoDao.Properties.Goods_id.eq(epcInfo.getGoods_id()))
                .list();
        if (null != list && list.size() > 0) {
            String json = new Gson().toJson(list.get(0));
            GoodsInfo goodsInfo = new Gson().fromJson(json, GoodsInfo.class);
            goodsInfo.setBrand_id(epcInfo.getBrand_id());

            addToSelectList(goodsInfo);
        } else {
            showErrorMsg("未查到该标签所属商品");
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (null == intent || null == intent.getStringExtra("from")) return;
        if (selectGoodsInfoList != null && selectGoodsInfoList.size() > 0) {
            selectGoodsInfoList.clear();
        }
        tv_select_all_count.setText("0");

    }
}
